package com.pan.kang.core;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Getter
@Setter
@Slf4j
public abstract class PostProcessEvent extends ApplicationEvent {

    private List<PostProcessTask> tasks;

    public PostProcessEvent(Object source) {
        super(source);
    }

    public PostProcessEvent(PostProcessEvent event) {
        super(event.source);
        this.tasks = event.tasks;
    }

    /**
     * 同步
     */
    public static PostProcessEvent syncEvent(Object source) {
        return new SyncEvent(source);
    }

    public static class SyncEvent extends PostProcessEvent {
        private SyncEvent(Object source) {
            super(source);
        }
    }

    /**
     * 异步
     */
    public static PostProcessEvent asyncEvent(Object source) {
        return new ASyncEvent(source);
    }

    public static class ASyncEvent extends PostProcessEvent {
        private ASyncEvent(Object source) {
            super(source);
        }
    }

    @Component
    public static class Listener {

        @Autowired
        private PostProcessExecuteManager executeManager;

        @EventListener
        public void syncEventProcessor(SyncEvent event) {
            PostProcessParam.Execute execute = new PostProcessParam.Execute();
            List<PostProcessTask> tasks = event.getTasks();
            execute.setTasks(tasks);
            executeManager.executeChained(execute);
        }

        @EventListener
        @Async
        public void syncEventProcessor(ASyncEvent event) {
            PostProcessParam.Execute execute = new PostProcessParam.Execute();
            List<PostProcessTask> tasks = event.getTasks();
            execute.setTasks(tasks);
            executeManager.executeChained(execute);
        }
    }
}
